<template>
  <div class="statistics">
    <div style="display: flex; justify-content: space-between">
      <div style="display: flex">
        <el-button type="primary" @click="chakanfenhong">查看分红</el-button>
        <el-button type="primary" @click="chakantongji">查看统计</el-button>
        <el-button type="primary" @click="exportExcel" style="margin-left: 10px;" v-if="qx">导出Excel</el-button>
      </div>
      <!-- 新增订单 -->

      <div style="display: flex">
        <el-date-picker v-model="dates" type="daterange" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期" @change="getAllGoods">
        </el-date-picker>
        <el-select v-model="select" placeholder="是否发货" style="width: 200px;" @change="getAllGoods">
          <el-option label="不排序" :value="0"></el-option>
          <el-option label="按客户名升序" :value="1"></el-option>
          <el-option label="按客户名降序" :value="2"></el-option>
          <el-option label="按版号升序" :value="3"></el-option>
          <el-option label="按版号降序" :value="4"></el-option>
        </el-select>
        <el-input style="width: 250px" v-model="input" placeholder="输入客户名称,版号,产品名称" @change="getAllGoods"></el-input>
        <!-- 搜索 -->
        <el-button icon="el-icon-search" circle style="margin-left: 20px" @click="getAllGoods"></el-button>
        <el-button style="margin-left: 40px" @click="clearSelect">{{ "重置" }}</el-button>
      </div>
    </div>

    <!-- 收益排行 -->
    <el-dialog style="margin-top: 0" :visible.sync="addFromDialog4" width="28%" :show-close="false" title="收益排行">
<!--      <el-select v-model="datebase" @change="dayPlay" placeholder="请选择日期">-->
<!--        <el-option v-for="item in options4" :key="item.value" :label="item.label" :value="item.value">-->
<!--        </el-option>-->
<!--      </el-select>-->
      <div style="display: flex">
        <el-select v-model="fenhong" @change="updateFenhong" placeholder="请选择">
          <el-option
              label="月"
              key="month"
              value="month"
          />
          <el-option
              label="年"
              key="year"
              value="year"
          />
        </el-select>
        <el-date-picker
            v-model="fenhongDate"
            :type="fenhong"
            :value-format="fenhong === 'month' ? 'yyyy-MM' : 'yyyy'"
            @change="chakanfenhong"
        >
        </el-date-picker>
      </div>
      <div style="height: 20px"></div>
      <div style="margin-bottom: 20px">累计分红金额: ￥{{ fenhongPrice.toFixed(2) }}元</div>

      <el-table :data="tableDataDay" border style="width: 100%">
        <el-table-column prop="rank" label="排名" width="80"> </el-table-column>
        <el-table-column prop="name" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="price" label="金额" width="120">
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 统计 -->
    <el-dialog style="margin-top: 0" :visible.sync="addFromDialog5" width="28%" :show-close="false" title="收益排行">
      <div style="display: flex">
        <el-select v-model="statistics" @change="updateTongji" placeholder="请选择">
          <el-option
              label="月"
              key="month"
              value="month"
          />
          <el-option
              label="年"
              key="year"
              value="year"
          />
        </el-select>
        <el-date-picker
            v-model="date"
            :type="statistics"
            :value-format="statistics === 'month' ? 'yyyy-MM' : 'yyyy'"
            @change="getStatisticsListByDate"
        >
        </el-date-picker>
      </div>
      <div style="height: 20px"></div>
      <div style="margin-bottom: 20px">累计总订单金额: ￥{{ zongjiPrice.toFixed(2) }}元</div>

      <el-table :data="getStatisticsList" border style="width: 100%">
        <el-table-column prop="sort" label="序号" width="180"></el-table-column>
        <el-table-column prop="name" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="orderCount" label="订单量" width="120">
        </el-table-column>
        <el-table-column prop="price" label="金额" width="120">
        </el-table-column>
      </el-table>
    </el-dialog>

    <div class="goods-table">
      <el-table class="table01" :data="tableData" v-loading="loading" border style="width: 100%" height="100%"
        :row-style="tableRowClassName">
        <el-table-column prop="i" label="序号" width="50" fit fixed>
        </el-table-column>
        <el-table-column prop="nameId" label="客户名称" fit width="100" v-show="qx" fixed>
        </el-table-column>
        <el-table-column prop="versionNumber" label="版号" fit width="90" fixed>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称" fit width="150" fixed>
        </el-table-column>
        <el-table-column prop="price" label="价格" fit width="55" v-show="qx">
        </el-table-column>
        <el-table-column prop="deliveryTime" label="交货日期" fit width="80">
        </el-table-column>
        <el-table-column prop="isSend" label="是否发货" fit width="80">
          <template slot-scope="scope">
            <div>{{ scope.row.isSend ? "是" : "否" }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="stOne" label="绘图" fit width="120">
        </el-table-column>
        <el-table-column prop="stTwo" label="切割" fit width="120">
        </el-table-column>
        <el-table-column prop="stThree" label="装刀" fit width="120">
        </el-table-column>
        <el-table-column prop="stFour" label="装线" fit width="120">
        </el-table-column>
        <el-table-column prop="stFive" label="打包" fit width="120">
        </el-table-column>
        <el-table-column prop="stSix" label="贴海绵" fit width="120">
        </el-table-column>
        <el-table-column prop="surPrice" label="附加费" fit width="70">
        </el-table-column>
        <el-table-column prop="count" label="错误原因" fit width="80">
        </el-table-column>
        <el-table-column prop="head" label="负责人" fit width="80">
        </el-table-column>
        <el-table-column prop="triggerSituation" label="处罚情况" fit width="80">
        </el-table-column>
        <el-table-column prop="deliveryId" label="出货单" fit width="80">
        </el-table-column>
        <el-table-column prop="count" label="备注" fit width="80">
        </el-table-column>
        <el-table-column prop="userId" label="操作" width="120" fixed="right" v-if="userInfo?.roleId == 1">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="more(scope.row)">
              更多
            </el-button>
            <el-button size="mini" type="text" @click="deleted(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage" :page-sizes="[20, 50, 100]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 查看更多 -->
    <el-dialog style="margin-top: 0" :visible.sync="addFromDialog2" width="74%" :show-close="false" title="更多信息">
      <el-form :model="genduo" :inline="true" ref="genduo" label-width="100px" class="demo-ruleForm">

        <el-form-item label="客户名称：" prop="name">
          <el-input type="text" v-model="genduo.nameId" placeholder="客户名称"></el-input>
        </el-form-item>
        <!-- 版号 -->
        <el-form-item label="版号：" prop="versionNumber">
          <el-input type="text" v-model="genduo.versionNumber" placeholder="版号"></el-input>
        </el-form-item>
        <!-- 产品名称 -->
        <el-form-item label="产品名称：" prop="productName">
          <el-input type="text" v-model="genduo.productName" placeholder="产品名称"></el-input>
        </el-form-item>
        <!-- 价格 -->
        <el-form-item label="价格：" prop="price">
          <el-input type="text" v-model="genduo.price" placeholder="价格"
            :readonly="Boolean(genduo.receivables)"></el-input>
        </el-form-item>
        <!-- 交货日期 -->
        <el-form-item label="交货日期" prop="deliveryTime">
          <el-input type="text" v-model="genduo.deliveryTime" placeholder="数量"></el-input>
        </el-form-item>
        <!-- 是否发货 -->
        <el-form-item label="是否发货：" prop="isIncludingTax">
          <el-select v-model="genduo.isSend" placeholder="是否发货">
            <el-option v-for="item in SexCategory" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 绘图 -->
        <el-form-item label="绘图：" prop="stOne">
          <el-select v-model="stData.stOne" multiple>
            <el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 切割 -->
        <el-form-item label="切割：" prop="stTwo">
          <div style="display: flex">
            <el-select v-model="stData.stTwo" multiple>
              <el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </el-form-item>

        <!-- 装刀 -->
        <el-form-item label="装刀：" prop="stThree">
          <el-select v-model="stData.stThree" multiple>
            <el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 装线 -->
        <el-form-item label="装线：" prop="stFour">
          <el-select v-model="stData.stFour" multiple>
            <el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 打包 -->
        <el-form-item label="打包：" prop="stFive">
          <el-select v-model="stData.stFive" multiple>
            <el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 贴海绵 -->
        <el-form-item label="贴海绵：" prop="stSix">
          <el-select v-model="stData.stSix" multiple>
            <el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 附加费 -->
        <el-form-item label="附加费：" prop="surPrice">
          <el-select v-model="stData.surPrice" multiple>
            <el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 错误原因 -->
        <el-form-item label="错误原因：" prop="count">
          <el-input type="text" v-model="genduo.count" placeholder="错误原因"></el-input>
        </el-form-item>

        <!-- 负责人 -->
        <el-form-item label="负责人：" prop="head">
          <el-input type="text" v-model="genduo.head" placeholder="负责人"></el-input>
        </el-form-item>

        <!-- 处罚情况 -->
        <el-form-item label="处罚情况：" prop="triggerSituation">
          <el-input type="text" v-model="genduo.triggerSituation" placeholder="处罚情况"></el-input>
        </el-form-item>

        <!-- 出货单 -->
        <el-form-item label="出货单：" prop="deliveryId">
          <el-input type="text" v-model="genduo.deliveryId" placeholder="出货单"></el-input>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注：" prop="count">
          <el-input type="text" v-model="genduo.count" placeholder="备注"></el-input>
        </el-form-item>

        <el-form-item label="账户：" prop="count" :readonly="genduo.receivables">
          <div v-if="genduo.accountName">{{ genduo.accountName }}</div>
          <el-select v-else v-model="genduo.accountId" placeholder="请选择" @focus="getAccount">
            <el-option v-for="item in accountList" :key="item.id" :label="item.accountName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div style="overflow: hidden;">
        <el-button type="primary" v-if="userInfo?.roleId == 1" style="float: right;margin:0 10px" @click="updateOrders"
          v-debounce>修改</el-button>
        <el-button type="primary" style="float: right;" @click="setreceivables" :disabled="Boolean(genduo.receivables)"
          v-debounce>{{
            genduo.receivables ? "已收款完成" : "确认收款"
          }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from "dayjs";
import {
  updateOrderStatus, //用户修改自己做的订单状态
  getOrderListByUser, //查询用户自己的订单
  getIncomeRanking, //收益排行
  getOrderCommission, //查询订单佣金
  setReceivables,
  selectAllCustom,
  updateRoot,
  deleteOrders,
  getAllOrderListByUser
} from "../../api/die.js";
import financeManage from "../../api/financeManage.js";
import user from "../../api/user.js";
import request from "@/axios";
export default {
  components: {},
  data() {
    return {
      qx: false,
      userid: "",
      yuer: "",
      hovering: false, // 用于判断鼠标是否在按钮上
      tableDataDay: [],
      //查询内容
      datebase: "-1",
      options4: [
        { value: "-1", label: "全部" },
        { value: "1", label: "今天" },
        { value: "7", label: "一周内" },
        { value: "30", label: "一个月内" },
        { value: "365", label: "一年内" },
      ],
      //搜索框的值
      input: "",
      dates: new Array(),
      select: 4,
      // 图片预览
      srcList: [],
      srcList2: [],
      //新增标题
      title: "新增产品",
      roleType: false,
      cover: "cover",
      // 显示表单
      addFromDialog: false,
      addFromDialog2: false,
      addFromDialog3: false,
      addFromDialog4: false,
      addFromDialog5: false,
      // 表格加载
      loading: false,
      //合同到期提醒
      dialogImageUrl: "",
      dialogVisible: false,
      genduo: "", //查看更多
      //新增订单数据
      prudproducts: {
        name: "",
        versionNumber: "",
        productName: "",
        price: "",
        deliveryTime: "",
        isSend: "",
      },
      tableData: void 0,
      //总数页
      total: 0,
      //是否发货
      SexCategory: [
        { value: 0, label: "否" },
        { value: 1, label: "是" },
      ],
      // 分页大小
      pageSize: 50,
      //记录当前页数
      currentPage: 1,
      //审核通过状态
      applyStatus: false,
      accountList: new Array(),
      userInfo: void 0,
      stData: {
        stOne: void 0,
        stTwo: void 0,
        stThree: void 0,
        stFour: void 0,
        stFive: void 0,
        surPrice: void 0,
        stSix: void 0
      },
      userList: new Array(),
      dayinInfo: new Array(),
      statistics: "month",
      fenhong: 'month',
      fenhongDate: new Intl.DateTimeFormat('fr-CA', {
        year: 'numeric',
        month: '2-digit'
      }).format(new Date()),
      date: new Intl.DateTimeFormat('fr-CA', {
        year: 'numeric',
        month: '2-digit'
      }).format(new Date()),
      getStatisticsList: [],
      fenhongPrice: 0,
      zongjiPrice: 0,
      exportExcelData: []
    };
  },
  mounted() {
    const userInfo = JSON.parse(localStorage.getItem("userInfo"));
    this.qx = userInfo.roleId == "10" ? false : true;
    this.userid = userInfo.nickName;
    this.userInfo = userInfo
    if (userInfo.roleId == "1" || userInfo.roleId == "10") {
      this.roleType = true;
    }
// 获取当前 UTC 时间基准
    const now = new Date();

// UTC 本月第一天（强制零时区日期）
    const utcFirstDay = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));

// UTC 本月最后一天（下月第0天）
    const utcLastDay = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0));

// 转换为纯日期字符串（不包含时区偏移）
    const firstDay = utcFirstDay.toISOString(); // "2025-02-01"
    const lastDay = utcLastDay.toISOString();   // "2025-02-28"

    console.log("本月第一天（UTC 基准）:", firstDay);
    console.log("本月最后一天（UTC 基准）:", lastDay);

    this.dates.push(firstDay);
    this.dates.push(lastDay);

    //查看分红排名
    // this.dayPlay();
    this.getAllGoods();
    //通过入库名称搜索框查询
  },
  //超级管理员显示功能
  methods: {
    updateTongji(val) {
      console.log(val);
      console.log(this.date);

      // 将this.fenhongDate转换为字符串
      const fenhongDateStr = String(this.date || '');

      if (val && val === 'year') {
        let lastIndexOf = fenhongDateStr.lastIndexOf("-");
        if (lastIndexOf !== -1) {
          this.date = new Date().getFullYear().toString();
        }
      } else if (val && val === 'month') {
        let lastIndexOf = fenhongDateStr.lastIndexOf("-");
        if (lastIndexOf === -1) {
          const month = (new Date().getMonth() + 1).toString().padStart(2, '0');
          this.date = `${new Date().getFullYear()}-${month}`;
        }
      }
      console.log(this.date);
      this.getStatistics();
    },
    updateFenhong(val) {
      console.log(val);
      console.log(this.fenhongDate);

      // 将this.fenhongDate转换为字符串
      const fenhongDateStr = String(this.fenhongDate || '');

      if (val && val === 'year') {
        let lastIndexOf = fenhongDateStr.lastIndexOf("-");
        if (lastIndexOf !== -1) {
          this.fenhongDate = new Date().getFullYear().toString();
        }
      } else if (val && val === 'month') {
        let lastIndexOf = fenhongDateStr.lastIndexOf("-");
        if (lastIndexOf === -1) {
          const month = (new Date().getMonth() + 1).toString().padStart(2, '0');
          this.fenhongDate = `${new Date().getFullYear()}-${month}`;
        }
      }
      console.log(this.fenhongDate);
      this.dayPlay();
    },
    getStatisticsListByDate(val) {
      console.log(`date: ${val}`);
      this.date = val;
      this.getStatistics();
    },
    chakanfenhong() {
      this.addFromDialog4 = true;
      this.dayPlay();
    },
    chakantongji() {
      this.addFromDialog5 = true;
      this.getStatistics();
    },
    //修改订单
    updateOrders() {
      const Data = {
        ...this.genduo,
        stOne: this.stData.stOne.join(","),
        stTwo: this.stData.stTwo.join(","),
        stThree: this.stData.stThree.join(","),
        stFour: this.stData.stFour.join(","),
        stFive: this.stData.stFive.join(","),
        stSix: this.stData.stSix.join(","),
        surPrice: this.stData.surPrice.join(","),
      }
      updateRoot(Data).then((data) => {
        if (data.code) {
          this.$message({
            type: "success",
            message: "修改成功",
          });
          //刷新数据
          this.getAllGoods();
        } else {
          this.$message({
            type: "error",
            message: "修改失败",
          });
        }
      });
    },
    getAccount() {
      financeManage.getAccountList({
        currentPage: 1,
        pageSize: 99,
      }).then(res => {
        this.accountList = res.data.accountList
      })
    },
    setreceivables() {
      if (this.genduo.accountId) {
        setReceivables({ id: this.genduo.id, accountId: this.genduo.accountId }).then(res => {
          this.$message(res.message)
          this.addFromDialog2 = false
          this.getAllGoods();
        })
      } else {
        this.$message("请选择账户")
      }
    },
    // 序号序列化
    serializeNumber(num) {
      if (num < 10) {
        return "00" + num;
      } else if (num < 100) {
        return "0" + num;
      } else {
        return num.toString();
      }
    },
    tableRowClassName({ row }) {
      if (row.receivables) {
        return { background: "#b3d8ff" };
      } else {
        return { background: "#ffe1e1" };
      }
    },
    // 格式化时间
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, "0");
      const day = d.getDate().toString().padStart(2, "0");
      const hours = d.getHours().toString().padStart(2, "0");
      const minutes = d.getMinutes().toString().padStart(2, "0");
      const seconds = d.getSeconds().toString().padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      // return `${year}-${month}-${day}`;
    },
    startTimeChange(value) {
      this.addEmployeeForm.startTime = dayjs(value).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      console.log("上架时间", dayjs(value).format("YYYY-MM-DD HH:mm:ss"));
    },
    endTimeChange(value) {
      this.addEmployeeForm.endTime = dayjs(value).format("YYYY-MM-DD HH:mm:ss");
      console.log("上架时间", dayjs(value).format("YYYY-MM-DD HH:mm:ss"));
    },

    //用户修改自己做的订单状态
    stUpdate(ch) {
      let type = "";
      let status = "2";
      if (ch == "check1") {
        type = 1;
        if (this.check1) {
          status = "1";
        }
      } else if (ch == "check2") {
        type = 2;
        if (this.check2) {
          status = "1";
        }
      } else if (ch == "check3") {
        type = 3;
        if (this.check3) {
          status = "1";
        }
      } else if (ch == "check4") {
        type = 4;
        if (this.check4) {
          status = "1";
        }
      } else if (ch == "check5") {
        type = 5;
        if (this.check5) {
          status = "1";
        }
      } else if (ch == "check6") {
        type = 6;
        if (this.check6) {
          status = "1";
        }
      }

      this.updcha(type, status);
    },
    handleMouseEnter(id) {
      getOrderCommission(id).then((data) => {
        this.yuer = data.data;
      });
      // 当鼠标移入时执行的方法
      console.log("Mouse entered!");
      // 这里可以调用其他需要执行的方法
    },
    handleMouseLeave() {
      // 当鼠标移出时执行的方法
      console.log("Mouse left!");
      // 这里也可以调用其他需要执行的方法
    },
    //查看更多
    async more(row) {
      this.userList = (await user.fuzzyQuery({
        currentPage: 1,
        pageSize: 999,
      })).data.userVoList
      this.stData.stOne = row.stOneN?.split(",") ?? new Array()
      this.stData.stTwo = row.stTwoN?.split(",") ?? new Array()
      this.stData.stThree = row.stThreeN?.split(",") ?? new Array()
      this.stData.stFour = row.stFourN?.split(",") ?? new Array()
      this.stData.stFive = row.stFiveN?.split(",") ?? new Array()
      this.stData.stSix = row.stSixN?.split(",") ?? new Array()
      this.stData.surPrice = row.surPriceN?.split(",") ?? new Array()
      this.addFromDialog2 = true;
      this.genduo = row;
    },
    async deleted(row) {
      await deleteOrders(row.id)
      this.getAllGoods()
    },

    //用户修改
    updcha(type, status) {
      updateOrderStatus(this.genduo.customId, type, status).then((data) => {
        if (data.code) {
          this.$message({
            type: "success",
            message: "修改成功",
          });
          //刷新数据
          this.getAllGoods();
        } else {
          this.$message({
            type: "error",
            message: "修改失败",
          });
        }
      });
    },

    // 新增产品
    submitaddEmployeeForm() {

    },

    dayPlay() {
      getIncomeRanking(this.fenhongDate).then((res) => {
        let price = 0;
        if (res) {
          // 为每一条数据添加排名序号,如果当前类型不是true,则不显示金额,只显示自己的金额
          let kt = [];
          res.data.forEach((item, index) => {
            if (!this.roleType) {
              if (item.userId != this.userid) {
                item.price = "****";
              }
            }

            let kb = {
              rank: index + 1,
              userId: item.userId,
              price: item.price,
              name: item.name
            };
            price += item.price;
            kt.push(kb);
          });
          this.tableDataDay = kt;

          //           this.tableDataDay = res.data.map((item, index) => ({
          //   rank: index + 1,
          //   userId: item.userId,
          //   price: item.price,
          // }));
        } else {
          this.$message("列表加载错误");
        }
        console.log("获取商品列表");
        this.fenhongPrice = price;
      });
    },
    //模糊查询信息
    likeEmployee() {
      getOrderListByUser(this.input, this.currentPage, this.pageSize).then((res) => {
        if (res.code) {
          this.tableData = res.data;
        } else {
          this.$message("列表加载错误");
        }
        console.log("获取商品列表");
      });
    },

    //初始化图片
    imgstatus() {
      let url =
        "https://kris-k.oss-cn-hangzhou.aliyuncs.com/kris/c179093a-41b0-4c70-bc1f-6e5973f35c98-jia.png";
      this.imageUrl = url;
      this.imageUrl2 = url;
    },

    // 查询列表
    getAllGoods() {
      getOrderListByUser(this.dates?.[0] ?? "", this.dates?.[1] ?? "", this.select, this.input, this.currentPage, this.pageSize).then(async res => {
        this.total = res.data.total;
        this.tableData = res.data.dieOrderList.map((item, index) => {
          item.i = (this.currentPage - 1) * this.pageSize + index + 1;
          return item;
        });
        this.tableData.map(async item => {
          const stList = ['stOne', 'stTwo', 'stThree', 'stFour', 'stFive', 'stSix', 'surPrice']
          for (const st of stList) {
            if (item[st] && item[st] != "") {
              const nameList = new Array()
              const list = item[st].split(',')
              for await (const value of list.map(i => user.getUser({ id: i })))
                nameList.push(value.data.nickName)
              item[st + 'N'] = item[st]
              item[st] = nameList.join(",")
            }
          }
        })
        const list = await selectAllCustom()
        // this.tableData.map(item => item.nameId = list.data.find(value => value.id == item.nameId).customName)
        this.tableData = this.tableData.map(item => {
          const value = list.data.find(value => value.id === item.nameId);
          if (value != null && value !== '') {
            // console.log(`找到匹配: item.nameId = ${item.nameId}, value.customName = ${value.customName}`);
            item.nameId = value.customName; // 修改 item.nameId 为 customName
          } else {
            // console.log(`未找到匹配: item.nameId = ${item.nameId}`);
            item.nameId = '';
          }

          return item; // 确保返回 item
        });
      });
    },
    // pageSize变化
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getAllGoods();
    },
    // 页码变化
    handleCurrentChange(curPage) {
      this.currentPage = curPage;
      this.getAllGoods();
    },
    async exportExcel() {
      let allOrderListByUser = await getAllOrderListByUser(this.dates?.[0] ?? "", this.dates?.[1] ?? "", this.select, this.input);
      let excelTableData = structuredClone(allOrderListByUser.data);

// 替换 ID 字段为名称字段
      excelTableData = excelTableData.map(item => {
        return {
          ...item,
          nameId: item.customName,       // 使用客户名称替换 nameId
          stOne: item.stOneNames,        // 使用 stOne 名称
          stTwo: item.stTwoNames,        // 使用 stTwo 名称
          stThree: item.stThreeNames,    // 使用 stThree 名称
          stFour: item.stFourNames,
          stFive: item.stFiveNames,
          stSix: item.stSixNames,
          surPrice: item.surPriceNames,
          isSend: item.isSend == 0 ? "是" : "否"
        };
      });

      const data = this.formatData(excelTableData);
      const wb = this.$XLSX.utils.book_new();
      const ws = this.$XLSX.utils.json_to_sheet(data);

// 设置列宽（根据名称字段调整）
      const columnWidths = [
        { wch: 5 },    // ID
        { wch: 20 },   // 客户名称（原 nameId）
        { wch: 20 },   // stOne 负责人
        { wch: 20 },   // stTwo 负责人
        { wch: 20 },   // stThree 负责人
        { wch: 15 },   // 是否发送
        // ...其他列
      ];
      ws['!cols'] = columnWidths;

      this.$XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      this.$XLSX.writeFile(wb, "刀模订单列表.xlsx");
    },
    formatData(data) {
      // 格式化表格数据，将对象数组转换为数组对象
      return data.map((item) => {
        const {
          nameId,
          versionNumber,
          productName,
          price,
          deliveryTime,
          isSend,
          stOne,
          stTwo,
          stThree,
          stFour,
          stFive,
          stSix,
          surPrice,
          count,
          head,
          triggerSituation,
          deliveryId
        } = item;
        return {
          客户名称: nameId,
          版号: versionNumber,
          产品名称: productName,
          价格: price,
          交货日期: deliveryTime,
          是否发货: isSend,
          绘图: stOne,
          切割: stTwo,
          装刀: stThree,
          装线: stFour,
          打包: stFive,
          贴海绵: stSix,
          附加费: surPrice,
          错误原因: count,
          负责人: head,
          处罚情况: triggerSituation,
          出货单: deliveryId
        };
      });
    },
    clearSelect() {
      this.input = ""
      this.getAllGoods()
    },
    selectable(row) {
      return Boolean(!row.receivables)
    },
    getStatistics() {
      request({
        method: "GET",
        url: '/dieOrder/getStatistics',
        params: {
          'yearOrMonth': this.date
        }
      })
      .then(res => {
        console.log(res);
        let data = res.data;
        let price = 0;

// 先计算总和
        data.forEach(item => {
          if (item.price != null) price += item.price;
        });

// 按price降序排序并添加序号
        this.getStatisticsList = data
            .sort((a, b) => b.price - a.price)
            .map((item, index) => ({
              ...item,
              sort: index + 1 // 根据排序结果编号
            }));

        this.zongjiPrice = price;
        // let data = res.data;
        // let price = 0;
        // for (let i = 0; i < data.length; i++) {
        //   if (data[i].price != null) {
        //     price += data[i].price;
        //   }
        // }
        // this.zongjiPrice = price;
        // this.getStatisticsList = res.data;
      })
    }
  },
};
</script>

<style>
.statistics {
  height: 100%;
}

.page {
  text-align: center;
}

.table01 .row-delivered {
  background-color: #ffe4e4;
  /* 红色未完成,0项 */
}

.table01 .row-pending {
  background-color: #36c0f4;
  /* 蓝色背景，两项 */
}

.table01 .row-ok {
  background-color: #d4ffdb;
  /* 绿色完成背景，表示已交付 */
}

.nameBox {
  overflow: auto;
  /* 显示滚动条 */
  z-index: 99;
  margin-top: 5px;
  font-size: 12px;
  text-align: center;
  width: 205px;
  height: 170px;
  border-radius: 5px;
  background-color: #ffffff;
  box-shadow: 0 6px 10px rgba(0, 0, 0, 0.2);
  position: absolute;
}

.goods-table {
  height: 94%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  margin-top: 10px;
}

.imgUrl {
  width: 100px;
  height: 100px;
  object-fit: cover;
  /* 保持原始宽高比，填充容器 */
}

.htimg {
  width: 150px;
  height: 150px;
  object-fit: cover;
  /* 保持原始宽高比，填充容器 */
}
</style>
